package zr.com.thread.sync;

import java.util.concurrent.TimeUnit;

public class Bank {
    private int money;
    private String name;

    public Bank(int money, String name) {
        this.money = money;
        this.name = name;
    }

    //存钱
    public synchronized void deposit(int money) {
        System.out.println("-----执行存钱-----");
        this.money += money;
        System.out.println("总额度：" + this.money);
    }

    //取款
    public synchronized boolean withdraw(int money) {
        System.out.println("-----执行取钱-----");
        if (this.money > money) {
            this.money = this.money - money;
            System.out.println("总额度：" + this.money);
            return true;
        } else {
            return false;
        }
    }

    public String getName() {
        return name;
    }


    public static void main(String[] args) {
        Bank bank = new Bank(100, "张三");
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        TimeUnit.MILLISECONDS.sleep(2);
                        bank.deposit(10);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        TimeUnit.MILLISECONDS.sleep(2);
                        bank.withdraw(50);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();
    }
}
